<?php
session_start(); // 开始会话

// 数据库配置信息
$servername = "localhost";
$db_username = "陌上";
$db_password = "123456";
$dbname = "陌上";

// 创建数据库连接
$conn = new mysqli($servername, $db_username, $db_password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 获取表单数据
$new_username = $_POST['new-username'] ?? '';
$new_password = $_POST['new-password'] ?? '';
$confirm_password = $_POST['confirm-password'] ?? '';

// 验证输入数据
if (empty($new_username) || empty($new_password) || empty($confirm_password)) {
    die("所有字段都是必填的");
}

if ($new_password !== $confirm_password) {
    die("两次输入的密码不一致");
}

// 检查用户名是否已存在
$sql = "SELECT id FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $new_username);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    die("用户名已存在，请选择另一个用户名");
}

// 加密密码
$hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

// 插入新用户信息到数据库
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $new_username, $hashed_password);

if ($stmt->execute()) {
    $_SESSION['username'] = $new_username; // 存储用户名到会话
    header("Location: welcome.php"); // 重定向到主页
    exit; // 确保在重定向后脚本停止执行
} else {
    echo "注册失败，请重试: " . $stmt->error;
}

// 关闭连接
$stmt->close();
$conn->close();
?>
